﻿using System;
using System.Windows.Controls;

using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;

namespace ControlExplorer
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            pivot.ItemsSource = ViewModel.Instance.Categories;

            SelectionTransition.Completed += SelectionTransition_Completed;
        }

        ListBox _lastlist;
        private void OnItemSelected(object sender, SelectionChangedEventArgs e)
        {
            _lastlist = (ListBox)sender;
            if (_lastlist.SelectedIndex != -1)
            {
                SelectionTransition.Begin();
                _lastlist.IsEnabled = false;
            }
        }

        void SelectionTransition_Completed(object sender, EventArgs e)
        {
            _lastlist.IsEnabled = true;
            var control = (ControlViewModel)_lastlist.SelectedItem;
            var controlIndex = ViewModel.Instance.Controls.IndexOf(control);
            if (control.Samples.Count == 1)
            {
                this.NavigationService.Navigate(new Uri(string.Format("/View/Pages/SamplePage" + App.XamlPageSuffix + ".xaml?control={0}&sample=0", controlIndex), UriKind.Relative));
            }
            else 
            {
                this.NavigationService.Navigate(new Uri(string.Format("/View/Pages/SampleListPage" + App.XamlPageSuffix + ".xaml?control={0}", controlIndex), UriKind.Relative));
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (_lastlist != null)
            {
                _lastlist.SelectedIndex = -1;
            }

            LoadTransition.Begin();
        }

        private void btnAbout_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/View/Pages/AboutPage" + App.XamlPageSuffix + ".xaml", UriKind.Relative));
        }

        private void btnSettings_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/View/Pages/SettingsPage" + App.XamlPageSuffix + ".xaml", UriKind.Relative));
        }
    }
}